package classes;
import interfaces.Categoria;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

import objetos.CategoriaObj;

public class CategoriaImpl implements Categoria {
	
	@Override
	public boolean atualizarCadastro(CategoriaObj categoria) {
		try {
			DataSource.init();
			Connection con = DataSource.getConnection();
			Statement stm = con.createStatement();
			stm.execute("UPDATE categorias SET "
					+ "nome = '" + categoria.getNome() + "'"
					+ " WHERE id = " + categoria.getId());
		} catch(IOException e) {
			System.out.println(e);
			return false;
		} catch(SQLException e) {
			System.out.println(e);
			return false;
		} catch(ClassNotFoundException e) {
			System.out.println(e);
			return false;
		}
		return true;
		}

	@Override
	public boolean efetuarCadastro(CategoriaObj categoria) {
		
		try {
			DataSource.init();
			Connection con = DataSource.getConnection();
			Statement stm = con.createStatement();
			stm.execute("INSERT INTO categorias VALUES (default,'"
					+ categoria.getNome() + "')" );
		} catch(IOException e) {
			System.out.println(e);
			return false;
		} catch(SQLException e) {
			System.out.println(e);
			return false;
		} catch(ClassNotFoundException e) {
			System.out.println(e);
			return false;
		}
		return true;
	}

	@Override
	public boolean removerCadastro(int id) {
		try {
			DataSource.init();
			Connection con = DataSource.getConnection();
			Statement stm = con.createStatement();
			stm.execute("DELETE FROM categorias WHERE id = " + id);
			
		} catch(IOException e) {
			System.out.println(e);
			return false;
		} catch(SQLException e) {
			System.out.println(e);
			return false;
		} catch(ClassNotFoundException e) {
			System.out.println(e);
			return false;
		}
		return true;
	}
	public LinkedList<CategoriaObj> buscarCategoriaPorNome (String Nome){
		LinkedList<CategoriaObj> Resultado;
		Resultado = new LinkedList<CategoriaObj>();
		try {
			DataSource.init();
			Connection con = DataSource.getConnection();
			Statement stm = con.createStatement();
			 
			ResultSet result = stm.executeQuery("SELECT * FROM categorias WHERE upper(nome) like '%" 
			  + Nome.toUpperCase() + "%'"); 
			while (result.next()){
				CategoriaObj Co = new CategoriaObj();
				Co.setId(result.getInt("ID"));
				Co.setNome(result.getString("Nome"));
				Resultado.add(Co);
			}
			result.close();
		} catch(IOException e) {
			System.out.println(e);
			return null;
		} catch(SQLException e) {
			System.out.println(e);
			return null;
		} catch(ClassNotFoundException e) {
			System.out.println(e);
			return null;
		}
		return Resultado;
	}
}
